package com.idea.cery.springboot1.controller;

import com.idea.cery.springboot1.service.AsyncService;
import io.swagger.annotations.Api;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

import java.util.concurrent.Future;

/**
 * @Author:cery
 * @Version 1.0
 * @Date:2020/4/9
 */
@Api(description = "异步执行任务")
@RestController
@RequestMapping("/ac")
public class AsyncController {

    @Autowired
    private AsyncService asyncService;

    @RequestMapping(value = "/async", method = RequestMethod.GET)
    public String async() {

        try {
            long start = System.currentTimeMillis();

            Future<String> dt1 = asyncService.doTask1();
            Future<String> dt2 = asyncService.doTask2();
            Future<String> dt3 = asyncService.doTask3();

            while (true) {
                //判断三个任务是否都执行完
                if (dt1.isDone() && dt2.isDone() && dt3.isDone()) {
                    break;
                }
                Thread.sleep(1000);
            }

            long end = System.currentTimeMillis();

            return "运行总耗时 " + (end - start) + " 毫秒";
        } catch (Exception e) {
            System.out.println(e.getMessage());
            return "运行出错 ";
        }

    }
}
